import { ref, reactive, toRefs, onMounted, defineComponent, getCurrentInstance } from 'vue';
import { useUsersStore } from '@/store/user';
import validator from '@/utils/validator';
import forgetPassword from '@/components/dialog/forgetPassword.vue';
export default defineComponent({
    name:'login',
    components: { forgetPassword },
    props:{},
    emits:[],
    setup (props, context)
    {
        const { proxy }:any = getCurrentInstance();
        const userStore = useUsersStore();
        let data = reactive({
            username:'',
            password:'',
            isChecked:false,
            loginLoading:false,
            haslogin:true,
            email:'',
            registerPassword:'',
            nickname:'',
            sex:'',
            count:5,
            dialogVisible:false,
            sexOptions:[{ label:'男', value:'0'}, {label:'女', value:'1'}],
            forgetVisible:false,
            ranking:0
        });

        interface userData {
            username?:string,
            password?:string
        }

        interface registerData {
            email:string,
            registerPassword:string,
            nickname:string,
            sex:string,
            syncId:string
        }
        
        let methods = {
            goLogin ()
            {
                data.dialogVisible = false;
                data.haslogin = true;
            },
            async login ()
            {
                let user:userData = {};
                user.username = data.username.trim();
                user.password = data.password.trim();
                if (user.username === '' || user.password === '')
                {
                    return proxy.$message.warning('账号密码未填写');
                }
                data.loginLoading = true;
                user.password = proxy.$utils.secret.md5encode(user.password);
                try
                {
                    const res = await userStore.login(user);
                    proxy.$message.success(res.data.msg);
                    methods.setDataCache(res.data.content);
                }
                catch (err:any)
                {
                    console.error('登录异常——' + err.message);
                }
                data.loginLoading = false;

            },
            async register ()
            {
                data.loginLoading = true;
                let registerObj:registerData = {
                    email:data.email,
                    registerPassword:data.registerPassword,
                    nickname:data.nickname,
                    sex:data.sex,
                    syncId:proxy.$utils.cache.syncId.get()
                };
                try 
                {
                    const a = validator.validateEmpty(registerObj);
                    const b = validator.validateEmail(data.email);
                    const c = validator.validatePwd(data.registerPassword);
                    const d =  validator.validateNickname(data.nickname);
                    await Promise.all([a, b, c, d]).catch((err:any) => 
                    {
                        proxy.$message.warning(err.message);
                        throw new Error(err.message);
                    });
                    registerObj.registerPassword = proxy.$utils.secret.Encrypt(data.registerPassword);
                    const res = await userStore.register(registerObj);
                    proxy.$message.success(res.data.msg);
                    data.username = res.data.content.username;
                    data.ranking = res.data.count;
                    for (let key in registerObj)
                    {
                        data[key] = '';
                    }
                    data.dialogVisible = true;
                }
                catch (err:any)
                {
                    console.error('注册异常——' + err.message);
                }
                data.loginLoading = false;
            },
            setDataCache (value)
            {
                proxy.$utils.cache.token.set(value.token);
                proxy.$utils.cache.userData.set(value);
                if (data.isChecked)
                {
                    proxy.$utils.cache.un.set(data.username);
                    proxy.$utils.cache.pwd.set(proxy.$utils.secret.Encrypt(data.password));
                }
                proxy.$router.replace({name:'home'});
            }
        };
        
        onMounted(() => 
        {
            if (proxy.$utils.cache.un.get() && proxy.$utils.cache.pwd.get())
            {
                data.isChecked = true;
                data.username = proxy.$utils.cache.un.get();
                data.password = proxy.$utils.secret.Decrypt(proxy.$utils.cache.pwd.get());
            }
        });

        return {
            ...toRefs(data),
            ...methods
        };
    }
});